package org.hibernate.tutorial;

import java.util.Date;
import java.util.List;

import org.hibernate.tutorial.domain.Event;
import org.hibernate.tutorial.domain.Person;
import org.hibernate.tutorial.util.HibernateUtil;

import org.hibernate.Session;


public class EventManager {

    public static void main(String[] args) {
    	
    	System.out.println("Hola Mundo 1 - " + args[0]);
    	
        EventManager mgr = new EventManager();
        
        if (args[0].equals("storeEvent")) {
            mgr.createAndStoreEvent("My Event", new Date());
        } 
        else if (args[0].equals("storePerson")) {
        	mgr.createAndStorePerson("Juani","Castillo",27);
        } 
        else if (args[0].equals("listEvents")) {
            List events = mgr.listEvents();
            for (int i = 0; i < events.size(); i++) {
                Event theEvent = (Event) events.get(i);
                System.out.println(
                        "Event: " + theEvent.getTitle() + " Time: " + theEvent.getDate()
                );
            } 
        }
        else if (args[0].equals("listPersons")) {
            List persons = mgr.listPersons();
            for (int i = 0; i < persons.size(); i++) {
                Person thePerson = (Person) persons.get(i);
                System.out.println(
                        "Person: " + thePerson.getFirstname() + 
                        " " + thePerson.getLastname() + 
                        " with: " + thePerson.getAge() + " years."
                );               
            } 
        }
        else if (args[0].equals("addpersontoevent")) {
            Long eventId = mgr.createAndStoreEvent("Ir a jugar", new Date());
            Long personId = mgr.createAndStorePerson("Bart", "Simpsons",15);
            mgr.addPersonToEvent(personId, eventId);
            System.out.println("Added person " + personId + " to event " + eventId);
        } 
        else if (args[0].equals("addEmailToPerson")) {
        	List persons = mgr.listPersons();
            Person thePerson = (Person)persons.get(1);
            String address = "jhonyz22@cromo.com";
            mgr.addEmailToPerson(thePerson.getId(), address);
            System.out.println("Added address " + address + " to person " + thePerson.getId());
        }
        else { System.out.println("SIN PARAMETRO"); }
        
        HibernateUtil.getSessionFactory().close();
        System.out.println("ADIOS!");
    } 
    
    private Long createAndStoreEvent(String title, Date theDate) {
    	System.out.println("ENTRA A CREATEANDSTOREEVENT");
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        System.out.println("getcurrentSession OK");
        session.beginTransaction();
        Event theEvent = new Event();
        theEvent.setTitle(title);
        theEvent.setDate(theDate);
        Long newId = (Long)session.save(theEvent);
        session.getTransaction().commit();
        System.out.println("commint");
        return newId;
    }
    
    private Long createAndStorePerson(String firstname, String lastname, int age) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        Person aPerson = new Person();
        aPerson.setFirstname(firstname);
        aPerson.setLastname(lastname);
        aPerson.setAge(age);
        Long newId = (Long)session.save(aPerson);
        session.getTransaction().commit();
        return newId;
    }
    
    private List listEvents(){
    	Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    	session.beginTransaction();
    	List result = session.createQuery("from Event").list();
    	session.getTransaction().commit();
		return result;
    }
    
    private List listPersons(){
    	Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    	session.beginTransaction();
    	List result = session.createQuery("from Person").list();
    	session.getTransaction().commit();
		return result;
    }
    
    private void addPersonToEvent(Long personId, Long eventId){
    	Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    	session.beginTransaction();
    	
    	Person aPerson = (Person) session
    					.createQuery("select p from Person p left join fetch p.events where p.id = :pid")
    					.setParameter("pid",personId)
    					.uniqueResult(); // Eager fetch the collection so we can use it detached
    	Event anEvent = (Event) session.load(Event.class, eventId);
    	
    	session.getTransaction().commit();
    	
    	// End of first unit of work
    	
    	aPerson.addToEvent(anEvent);; // aPerson (and its collection) is detached
    	
    	// Begin second unit of work
    	
    	Session session2 = HibernateUtil.getSessionFactory().getCurrentSession();
        session2.beginTransaction();
        session2.update(aPerson); // Reattachment of aPerson

        session2.getTransaction().commit();
    }
    
    private void addEmailToPerson(Long personId, String emailAddress) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        Person aPerson = (Person) session.load(Person.class, personId);
        // adding to the emailAddress collection might trigger a lazy load of the collection
        aPerson.getEmailAddresses().add(emailAddress);

        session.getTransaction().commit();
    }
    
}


